package com.topnav.mc.interceptor;

import com.topnav.mc.admin.security.config.JwtProperties;
import com.topnav.mc.common.Constant;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 说明：Token 拦截器
 * 把token 存入 MDC，使用时先从MDC取出，再由缓存取用户单位的权限
 * @类名: TraceInterceptor
 * 需在 WebMvcConfigurationSupport 中注入才生效
 * 与Spring security 有冲突（可以启动，但如访问swagger的 doc.html 都被拦截了）
 *  * 暂时不明白原因
 * @author   kenny
 * @Date	 2019年12月27日下午6:04:24
 */
@Component
public class TraceInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private JwtProperties jwtProperties;

    MDC.MDCCloseable mdcClose;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.err.println(request.getRequestURI());
        String token = request.getHeader(jwtProperties.getHeader());
        if (StringUtils.isEmpty(token)){
            token = request.getParameter(jwtProperties.getHeader());
        }

        //traceCode存入MDC
        //String traceCode = IdUtils.getIdByUUID();
        //handler 结束后移除
        mdcClose = MDC.putCloseable(Constant.MDC_TOEKN, token);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
        //从MDC移除traceCode
        if (mdcClose != null){
            mdcClose.close();
        }
    }

}
